package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.RedisKeysStandard;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate template;
    @Override
    public void cacheVerifyCode(String key, String value, Long time) {
        template.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String s) {
        return template.opsForValue().get(s);
    }

    @Override
    public void cacheUserToken(String key, String value, Long time) {
        template.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public UserInfo getUserToken(String key) {
        // token不存在直接返回null
        if (!StringUtils.hasLength(key)){
            return null;
        }
        key = RedisKeysStandard.USER_TOKEN.addKeyMessage(key);
        if (template.hasKey(key)){
            String userInfo = template.opsForValue().get(key);
            if (StringUtils.hasLength(userInfo)) {
                UserInfo userInfoObj = JSON.parseObject(userInfo, UserInfo.class);
                // 重置存储的时间
                template.expire(key,RedisKeysStandard.USER_TOKEN.getTime(),TimeUnit.SECONDS);
                return userInfoObj;
            }
        }
        return null;
    }

    @Override
    public void cacheVerifyCodeFreq(String key, String value, Long time) {
        template.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCodeFreq(String key) {
        return template.opsForValue().get(key);
    }
}
